package com.buaa.sax_xml;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import util.HttpUtil;

public class MainActivity extends AppCompatActivity {
    private  Handler handler;
    private ListView listView;
    List<HashMap<String,String>> list= new ArrayList<HashMap<String, String>>();;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=(ListView)findViewById(R.id.listView);
        final String path="http://192.168.1.104:8080/android_xf_project/person.xml";
        handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
               if (msg.what==1){
                    HashMap<String,String> map= (HashMap<String, String>) msg.obj;
                   Log.i("sgk",map.toString());
                   list.add(map);
               }
                SimpleAdapter simpleAdapter=new SimpleAdapter(MainActivity.this,list,R.layout.item,new String[]{"name","age"},new int[]{R.id.name,R.id.age});
                listView.setAdapter(simpleAdapter);
            }
        };
        new Thread(){
            @Override
            public void run() {
                InputStream inputStream= HttpUtil.getXml(path);
                try {
                    List<HashMap<String,String>> list=SaxService.readXML(inputStream,"person");
                    for (HashMap<String,String> map:list){
                        Message message=Message.obtain();
                        message.obj=map;
                        message.what=1;
                      handler.sendMessage(message);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }.start();

    }
}
